package tmt.usercenter.web.plugin.editormodel;

import com.tmt.datatable.editor.IFileDataHolder;
import com.tmt.datatable.editor.IUploadActionHandler;
import com.tmt.datatable.model.UploadedFile;
import com.tmt.fileservice.FileSaveMode;
import com.tmt.fileservice.IFileDataResolver;
import com.tmt.fileservice.IFileDispatcher;
import com.tmt.fileservice.IFileService;
import com.tmt.helper.ReflectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import tmt.usercenter.web.plugin.filesevice.FileDataResolver;

import java.text.MessageFormat;

/**
 * Created by ThreeManTeam on 2017/6/6.
 */
public class DefaultUploadActionHandler implements IUploadActionHandler {

    private MessageSource messageSource;

    private IFileService fileService;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public void setFileService(IFileService fileService) {
        this.fileService = fileService;
    }

    @Override
    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    @Override
    public <T> UploadedFile saveFile(Class<T> clazz, String fieldName, IFileDataHolder iFileDataHolder) {
        UploadedFile uploadedFile = new UploadedFile();
        try {
            Class<?> targetClazz = clazz;
            String targetFieldName = fieldName;
            if (targetFieldName.contains(".")){
                String tmpFieldName = targetFieldName.replace("[]", "");
                targetClazz = ReflectHelper.getActualClassByFieldPath(clazz, tmpFieldName, false, true);
                String[] names = fieldName.split("\\.");
                targetFieldName = names[names.length -1];
            }

            IFileDispatcher dispatcher = fileService.getFileDispatcher();
            String filePath = dispatcher.getFilePath(targetClazz, targetFieldName, iFileDataHolder.getFileName(), FileSaveMode.TEMPARARY);

            IFileDataResolver resolver = new FileDataResolver(iFileDataHolder);
            fileService.save(filePath, resolver);

            //不设置ID，则EditorModel会自动使用文件名称（*.*）作为ID的默认值。
            //uploadedFile.setId();
            uploadedFile.setFilePth(filePath);
            uploadedFile.setFileUrl(dispatcher.filePathToUrl(filePath));
        } catch (Exception ex) {
            logger.debug(MessageFormat.format("保存上传文件{0}异常：{1}", iFileDataHolder.getFileName(), ex.getMessage()));
        }
        return uploadedFile;
    }


}
